<template>
	<view class="progress-container">
		<!-- 进度步骤 -->
		<view class="progress-steps">
			<up-steps :current="currentStepIndex" direction="column">
				<up-steps-item v-for="(item, index) in progressList" :key="index" :title="''">
					<template #desc>
						<view class="step-content" :class="{ clickable: item.clickable }"
							@click="handleStepClick(item)">
							<text class="step-title">{{ item.title }}</text>
							<text class="step-time">{{ item.time }}</text>
							<text class="step-desc" v-if="item.description">{{ item.description }}</text>
						</view>
					</template>
				</up-steps-item>
			</up-steps>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getContractDetailApi } from '@/api/signs.js'
import { useContractStore } from '@/store/contract.js'

// 状态管理
const contractStore = useContractStore()

// 响应式数据
const contractData = ref({}) // 存储完整的签约数据
const contractId = ref('') // 签约记录ID

// 根据签约状态动态生成进度列表
const progressList = computed(() => {
	let state = 1
	if (contractData.value.state !== undefined) {
		state = contractData.value.state
	} else if (contractStore.currentContractState !== undefined) {
		state = contractStore.currentContractState
	}
	const teamName = contractData.value.teamName || contractStore.contractApplication?.teamName || '签约团队'
	const submitTime = contractData.value.applyTime || contractStore.contractApplication?.submitTime || new Date().toLocaleString('zh-CN')

	const steps = []

	// 按照时间顺序添加步骤（从早到晚）

	// 第一步：申请提交（所有状态都有）
	steps.push({
		title: '签约申请提交成功',
		description: `签约团队：${teamName}`,
		time: submitTime,
		clickable: false
	})

	// 根据状态添加后续步骤
	if (state === 0) {
		// 已驳回状态：申请提交 → 申请被驳回
		steps.push({
			title: '签约申请被驳回',
			description: `签约团队：${teamName}`,
			time: contractData.value.rejectTime || submitTime,
			clickable: false
		})
	} else if (state >= 2) {
		// 待支付及以上状态：申请提交 → 审核通过
		steps.push({
			title: '医生审核通过，等待支付',
			description: `签约团队：${teamName}`,
			time: contractData.value.reviewTime || submitTime,
			clickable: state === 2 // 只有待支付状态才可点击
		})

		if (state >= 3) {
			// 已签约及以上状态：申请提交 → 审核通过 → 签约生效
			steps.push({
				title: '签约生效',
				description: `签约团队：${teamName}`,
				time: contractData.value.effectiveDate || new Date().toLocaleString('zh-CN'),
				clickable: false
			})

			if (state === 4) {
				// 待续约状态：申请提交 → 审核通过 → 签约生效 → 待续约
				steps.push({
					title: '签约已到期，待续约',
					description: `签约团队：${teamName}`,
					time: contractData.value.expireTime || new Date().toLocaleString('zh-CN'),
					clickable: true // 可以点击续约
				})
			}
		}
	}

	return steps
})

// 计算当前步骤索引
const currentStepIndex = computed(() => {
	let state = 1
	if (contractData.value.state !== undefined) {
		state = contractData.value.state
	} else if (contractStore.currentContractState !== undefined) {
		state = contractStore.currentContractState
	}

	// 根据状态计算当前步骤索引
	let stepIndex = 0
	switch (state) {
		case 0: // 已驳回：显示到第1步（申请被驳回）
			stepIndex = 1
			break
		case 1: // 待审核：显示到第0步（申请提交）
			stepIndex = 0
			break
		case 2: // 待支付：显示到第1步（审核通过）
			stepIndex = 1
			break
		case 3: // 已签约：显示到第2步（签约生效）
			stepIndex = 2
			break
		case 4: // 待续约：显示到第3步（待续约）
			stepIndex = 3
			break
		default:
			stepIndex = 0
	}

	return stepIndex
})

// 获取签约详情
const getContractDetail = async () => {
	if (!contractId.value) {
		// 如果没有contractId，尝试从状态机获取数据
		if (contractStore.hasContractApplication) {
			contractData.value = {
				...contractStore.contractApplication,
				teamName: contractStore.contractApplication.teamName,
				state: contractStore.contractApplication.state
			}
		}
		return
	}

	uni.showLoading({
		title: '加载中...'
	})

	const res = await getContractDetailApi({
		_id: contractId.value
	})

	uni.hideLoading()

	if (res.code === 200) {
		const data = res.data

		// 存储完整的签约数据
		contractData.value = {
			contractId: contractId.value,
			teamName: data.teamId?.name || '',
			doctorName: data.doctorId?.name || '',
			organization: data.organizationId?.name || '',
			servicePackage: data.servicePackId?.name || '',
			price: data.servicePackId?.price || '0',
			period: data.servicePackId?.period || '1年',
			type: data.type || '',
			remark: data.remark || '',
			applyTime: data.applyTime || '',
			effectiveDate: data.effectiveDate || '',
			state: data.state !== undefined ? data.state : 1
		}

		// 更新状态机中的签约状态
		contractStore.updateContractState(data.state !== undefined ? data.state : 1)
	} else {
		uni.showToast({
			title: res.message || '获取签约详情失败',
			icon: 'none'
		})
	}
}

// 页面加载时接收参数
onLoad((options) => {
	if (options.contractId) {
		contractId.value = options.contractId
		// 获取完整签约详情
		getContractDetail()
	} else {
		// 如果没有contractId，尝试从状态机获取数据
		getContractDetail()
	}
})

// 处理步骤点击事件
const handleStepClick = (item) => {
	if (!item.clickable) {
		return
	}

	let state = 1
	if (contractData.value.state !== undefined) {
		state = contractData.value.state
	} else if (contractStore.currentContractState !== undefined) {
		state = contractStore.currentContractState
	}

	// 根据步骤标题和当前状态判断跳转
	if (item.title.includes('等待支付') && state === 2) {
		// 待支付状态，跳转到支付页面
		const targetContractId = contractId.value || contractStore.contractApplication?.contractId
		if (targetContractId) {
			uni.navigateTo({
				url: `/homepackge/pages/payPage/payPage?contractId=${targetContractId}`
			})
		} else {
			uni.showToast({
				title: '签约信息缺失',
				icon: 'none'
			})
		}
	}
}



</script>

<style scoped>
.progress-container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.progress-steps {
	padding: 40rpx 30rpx;
}

.step-content {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	padding: 8rpx 0;
	border-radius: 8rpx;
	transition: all 0.3s ease;
}

.step-content.clickable {
	cursor: pointer;
	padding: 12rpx 16rpx;
	background-color: rgba(74, 144, 226, 0.05);
	border: 1rpx solid rgba(74, 144, 226, 0.2);
}

.step-content.clickable:active {
	background-color: rgba(74, 144, 226, 0.1);
	transform: scale(0.98);
}

.step-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 8rpx;
	line-height: 1.4;
}

.step-time {
	font-size: 24rpx;
	color: #999;
}

.step-desc {
	font-size: 28rpx;
	color: #666;
	line-height: 1.4;
}

.step-content.clickable .step-title {
	color: #333;
}

.step-content.clickable .step-time {
	color: #4A90E2;
}

.step-content.clickable .step-desc {
	color: #333;
}
</style>
